﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MetaDemo
{
    public class UIHelper
    {

        /// <summary>
        /// Return the first encountered parent object with the given type.
        /// "First" is calculated from the bottom, i.e. from the control.
        /// If none can be found, null is returned.
        /// </summary>
        /// <param name="control">The control whose parent is needed.</param>
        /// <param name="parentType">The type of the parent, that must match for a valid result.</param>
        /// <returns>Either the parent object or null.</returns>
        public static Object FindParentWithType(Control control, Type parentType) {
            if (parentType.Equals(control.GetType()))
                return control;
            
            if (null == control.Parent)
                return null;

            return FindParentWithType(control.Parent, parentType);
        }



        public static Form GetFormForControl(Object c)
        {
            if (c is Control)
            {
                Control control = c as Control;
                if (null != control.FindForm())
                    return control.FindForm();
            }

            if (c is ToolStripItem)
            {
                var tsi = (ToolStripItem)c;
                if (null != tsi.Owner)
                {
                    return GetFormForControl(tsi.Owner);
                }
            }

            return null;
        }

    }
}
